# coding=utf-8

'''关于容器的相关管理功能'''
import json

from django.http import HttpResponse
from django.shortcuts import render

from dockerManagerApp import models
from dockerManagerApp.model.base.rpc_client import rpcClientFunction


def container_ManagerFun(request):
    '''在这里添加获取所有容器列表'''
    if request.method == 'GET':
        container_list = []

        # 先获取在线节点列表
        listValue = models.HostManager.objects.filter().values()
        count = 0
        for i in range(len(listValue)):
            hostname = listValue[i].get('hostname')
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '0':  # 0 代表在线
                rpclient = rpcClientFunction(hostaddr)
                retu = rpclient.getAllContainers({})

                dataList = json.loads(retu.get('data'))
                for i in range(len(dataList)):
                    itemContainer = {}
                    itemContainer['hostname'] = hostname
                    itemContainer['hostaddr'] = hostaddr

                    count = count + 1
                    Names = dataList[i].get('Names')
                    Id = dataList[i].get('Id')
                    Id = Id[0:12]
                    Status = dataList[i].get('Status')
                    if Status.find("Exited") >= 0:
                        Status = '已停止'
                    elif Status.find("Up") >= 0:
                        Status = '运行中'
                    else:
                        Status = '未知状态'
                    itemContainer['count'] = count
                    itemContainer['Names'] = Names
                    itemContainer['Id'] = Id
                    itemContainer['Status'] = Status
                    container_list.append(itemContainer)

        return render(request, 'containermanager.html', {'container_list': container_list})
    elif request.method == 'POST':
        ret = {'status': True, 'error': None, 'data': None}
        action = request.POST.get('action')
        id = request.POST.get('id')
        hostaddress = request.POST.get('hostaddress')
        print('hostaddress,id,action', hostaddress, action)

        listValue = models.HostManager.objects.filter().values()
        for i in range(len(listValue)):
            hostaddr = listValue[i].get('hostaddr')
            if hostaddr == hostaddress:
                status = listValue[i].get('status')
                if status == '1':
                    ret['status'] = False
                    ret['error'] = u'该节点状态为离线'
                    return HttpResponse(json.dumps(ret))
                break

        if action == '停止':
            rpclient = rpcClientFunction(hostaddress)
            arg_dict = {}
            arg_dict['id'] = id
            rpclient.stopContainer(arg_dict)
        elif action == '启动':
            rpclient = rpcClientFunction(hostaddress)
            arg_dict = {}
            arg_dict['id'] = id
            rpclient.start_Container(arg_dict)
        elif action == '删除':
            rpclient = rpcClientFunction(hostaddress)
            arg_dict = {}
            arg_dict['id'] = id
            rpclient.delete_Container(arg_dict)
        elif action == 'add':
            rpclient = rpcClientFunction(hostaddress)

            container_arg_name = request.POST.get('container_arg_name')
            container_arg_nodes = request.POST.get('container_arg_nodes')
            container_arg_image = request.POST.get('container_arg_image')
            container_arg_command = request.POST.get('container_arg_command')
            container_arg_core = request.POST.get('container_arg_core')
            container_arg_mem = request.POST.get('container_arg_mem')
            container_arg_ports = request.POST.get('container_arg_ports')
            container_arg_dirs = request.POST.get('container_arg_dirs')
            action = request.POST.get('action')
            hostaddress = request.POST.get('hostaddress')

            arg_dict = {
                'container_arg_name':container_arg_name,
                'container_arg_nodes':container_arg_nodes,
                'container_arg_image':container_arg_image,
                'container_arg_command':container_arg_command,
                'container_arg_core':container_arg_core,
                'container_arg_mem':container_arg_mem,
                'container_arg_ports':container_arg_ports,
                'container_arg_dirs':container_arg_dirs,
                'action':action,
                'hostaddress':hostaddress,
            }

            rpclient.create_Container(arg_dict)

        return HttpResponse(json.dumps(ret))


def containerManagerFun(request):
    ret = {'status': True, 'error': None, 'data': None}

    nodeName = request.GET.get('node_name')
    action = request.GET.get('action')
    print(nodeName, action)

    hostaddr = ""
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostname = listValue[i].get('hostname')
        if hostname == nodeName:
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '1':
                ret['status'] = False
                ret['error'] = u'该节点状态为离线'
                return HttpResponse(json.dumps(ret))
            break

    if hostaddr == "":
        ret['status'] = False
        ret['error'] = u'没有查询到节点ip'
        return HttpResponse(json.dumps(ret))
    else:
        rpclient = rpcClientFunction(hostaddr)
        retu = rpclient.getAllContainers({})
        print(retu)
        containerList = []
        dataList = json.loads(retu.get('data'))
        for i in range(len(dataList)):
            containerList.append(dataList[i].get('Names'))

        ret['data'] = containerList
        return HttpResponse(json.dumps(ret))
